<!DOCTYPE>
<!--解决idea thymeleaf 表达式模板报红波浪线-->
<!--suppress ALL -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <!--    <title>实时日志</title>-->
    <!-- jquery -->
    <!--    <script src="../static/js/jquery-1.9.1.min.js"></script>-->
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
    <script>
        // Fallback to loading jQuery from a local path if the CDN is unavailable
        (window.jQuery || document.write('<script src="/scripts/jquery-1.9.0.min.js"><\/script>'));
    </script>
</head>
<body>
<!-- 标题 -->
<h1 style="text-align: center;" id="titleName">实时日志</h1>
<div>
    <input id="sockectUrl" th:value="${socketUrl}" hidden="hidden"/>
    <input id="targetName" th:value="${targetName}" hidden="hidden"/>
</div>

<!-- 显示区 -->
<div id="loggingText" contenteditable="true"
     style="width:100%;height: 800px;background-color: ghostwhite; overflow: auto;"></div>

<!-- 操作栏 -->
<div style="text-align: center;">
    <button onclick="$('#loggingText').text('')" style="color: green; height: 35px;">清屏</button>
    <button onclick="$('#loggingText').animate({scrollTop:$('#loggingText')[0].scrollHeight});"
            style="color: green; height: 35px;">滚动至底部
    </button>
    <button onclick="if(window.loggingAutoBottom){$(this).text('开启自动滚动');}else{$(this).text('关闭自动滚动');};window.loggingAutoBottom = !window.loggingAutoBottom"
            style="color: green; height: 35px; ">开启自动滚动
    </button>
</div>
</body>
<script>
    //websocket对象
    let websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        let socketUrl = $("#sockectUrl").val()
        let targetName = $("#targetName").val()
        $("#titleName").html(targetName);
        console.log("socketUrl地址：" + socketUrl)
        websocket = new WebSocket(socketUrl)
    } else {
        console.error("不支持WebSocket");
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        console.error("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        console.log("WebSocket连接成功")
    };

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        //追加
        if (event.data) {

            //日志内容
            let $loggingText = $("#loggingText");
            $loggingText.append(event.data);

            //是否开启自动底部
            if (window.loggingAutoBottom) {
                //滚动条自动到最底部
                $loggingText.scrollTop($loggingText[0].scrollHeight);
            }
        }
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        console.log("WebSocket连接关闭")
    };
</script>
</html>
